package com.ftx.controller.test.spring.transactions;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * Created by fengtingxin on 2020/5/19.
 */
@EnableTransactionManagement
@ComponentScan("com.ftx.controller.test.spring.transactions")
@Configuration
public class TxConfig {

    /**
     * 数据源
     * @return
     * @throws Exception
     */
    @Bean
    public DataSource dataSource() throws Exception{
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setUser("root");
        comboPooledDataSource.setPassword("123456");
        comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/fengtingxin");
        comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
        return comboPooledDataSource;
    }

    /**
     * 简化增删盖茶的操作
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate() throws Exception{
        //这里直接调用方法，并不会重新创建bean， Configuration 是给容器中增加组件，多次调用，都只是从容器中找到组件
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
        return jdbcTemplate;
    }

    @Bean
    public PlatformTransactionManager platformTransactionManager() throws Exception{
        return new DataSourceTransactionManager(dataSource());
    }
}
